package org.autumn.netty;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferExam {
    public static void main(String[] args) {
        // 模拟网络通信
        ByteBuffer allocate = ByteBuffer.allocate(32);
        allocate.put("hello world\ni am zhangsan\nhow ".getBytes());
        split(allocate);
        allocate.put("are you?\n".getBytes());
        split(allocate);

    }

    // 解决网络通信中的粘包半包的问题
    public static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            // 读取到了换行符
            if (source.get(i) == '\n') {
                int len = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(len);
                for (int j = 0; j < len - 1; j++) {
                    target.put(source.get());
                }
                // 丢弃 \n  换行符
                source.get();
                target.flip();
                System.out.println(StandardCharsets.UTF_8.decode(target));
            }
        }
        source.compact();
    }
}
